#include "Map.h"
#include "../data/GameInfo.h"

bool Map::GenerateTileMapTexture()
{
    SDL_Texture *texTileSet = GameInfo::Instance().texturePool[TexId::TEX_MAP];
    texMap = SDL_CreateTexture(GAME_RENDERER, SDL_PIXELFORMAT_ARGB8888,
                               SDL_TEXTUREACCESS_TARGET, w, h);
    if (!texMap) { return false; }

    SDL_SetTextureBlendMode(texMap, SDL_BLENDMODE_BLEND);
    SDL_SetRenderTarget(GAME_RENDERER, texMap);
    for (int y = 0; y < h / SIZE_TILE; y++) {
        for (int x = 0; x < w / SIZE_TILE; x++) {
            SDL_Rect src = {SIZE_TILE * (y % 10), 0, SIZE_TILE, SIZE_TILE};
            SDL_Rect dst = {x * SIZE_TILE, y * SIZE_TILE, SIZE_TILE, SIZE_TILE};
            SDL_RenderCopy(GAME_RENDERER, texTileSet, &src, &dst);
        }
    }
    SDL_SetRenderTarget(GAME_RENDERER, nullptr);
    return true;
}

void Map::InMap(GameVector &position) const
{
    if (position.x < 0) position.x = 0;
    if (position.x > w) position.x = w;
    if (position.y < 0) position.y = 0;
    if (position.y > h) position.y = h;
}

void Map::OnRender()
{
    SDL_Rect src = {0, 0, w, h};
    SDL_Rect dst = {0, 0, w, h};
    SDL_RenderCopy(GAME_RENDERER, texMap, &src, &dst);
}